from datetime import datetime

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
import GlobalVariable
token = "YApDiYrCCZW_4lXiuVb4nyBoBZurIZ9sxQh1ToYhpPqL46AENXPTyDyBoj4TCu3tLHnBSINWWSNKFjUwv8IHsA=="
org = "userxdd"
bucket = "test2"
test_bucket = "test2"
def delet(client):
    # 最开始的时间 1970-01-01 00:00:00
    start = datetime.utcfromtimestamp(0)
    stop = datetime.now()
    print(start, stop)
    # client.delete_api().delete(start, stop, '_value="2023-08-27T16:39:50Z"', bucket=bucket, org=org)
    # client.delete_api().delete(start, stop, '_time="2023-8-28 00:39:50"', bucket=bucket, org=org)
    client.delete_api().delete(start, stop, '_measurement="JD"', bucket=bucket, org=org)

# 添加
def add(client,measurement,tags,fields):


    # 同步写
    write_api = client.write_api(write_options=SYNCHRONOUS)
    if tags==None:
        tags={"default:"}


    ##
    sequence=""
    for x in fields:
        for y in x :
            sequence = Point(measurement) \
                .field(y, x[y]) \
                .tag('mac',GlobalVariable.device_list[tags]['device_name'])\
                .time(datetime.utcnow(), WritePrecision.NS)
            # sequence = {"measurement": measurement,  "fields": x }
            write_api.write(test_bucket, org, sequence)
            print("成功", x,GlobalVariable.device_list[tags]['device_name'])

    ### 添加tag的方式 tags可以存在多个 还是在同一个数据项中
    ## 1.可以直接添加字符
    # sequence = Point("JD") \
    #     .tag("used_percent2", 24.43234542) \
    #     .field("used_percent2", 14) \
    #     .time(datetime.utcnow(), WritePrecision.NS)
    ## 2.也可以传入对象
    # sequence= {"measurement": measurement, "tags": tags,"fields": fields}
    ## 3.直接传入   meansur    tag                 filed
    # sequence = ["h2o_feet,location=coyote_creek water_level=2.0 2",
    #              "h2o_feet,location=coyote_creek water_level=3.0 3"]



    # 写入方法2 （推荐这种）
    # point = Point("mem") \
    #     .tag("host", "host1") \
    #     .field("used_percent", 24.43234543) \
    #     .time(datetime.utcnow(), WritePrecision.NS)
    # write_api.write(bucket, org, point)

# 询问
def query(client):
    # query = 'from(bucket: "test2")   |> range(start: 2023-10-01T10:46:21.374Z) |> filter(fn: (r) => r["_measurement"] == "JD" and r._value < 10000) |> filter(fn: (r) => r["_field"] == "download_num" or r["_field"] == "upload_num") |> aggregateWindow(every: 1h0m0s, fn: mean, createEmpty: true) |> yield(name: "mean")'
    query='from(bucket: "test2") |> range(start: -90s) |> filter(fn: (r) => r["_measurement"] == "JD")  |> yield(name: "mean")'

    tables = client.query_api().query(query, org=org)
    for table in tables:
        for record in table.records:
            print(record)


def creat_client():
    client = InfluxDBClient(url="http://ip.dinxian.cn:8086/", token=token, org="userxdd")
    return client


# 添加
def add2(client,measurement,tags,fields):
    # 同步写
    write_api = client.write_api(write_options=SYNCHRONOUS)
    if tags==None:
        tags={"default:"}

    ### 不添加tag的方式

    year = 2023
    month = 9
    day = 1
    hour = 8
    minute = 30
    second = 0

    # 生成 datetime 对象
    custom_time = datetime(year, month, day, hour, minute, second)
    ##
    sequence=""
    for x in fields:
        for y in x :
            sequence = Point(measurement) \
                .field(y, x[y]) \
                .time(datetime.utcnow(), WritePrecision.NS)
                # .time(custom_time, WritePrecision.NS)

            # sequence = {"measurement": measurement,  "fields": x }
            write_api.write(test_bucket, org, sequence)
            print("成功", x)

    ### 添加tag的方式 tags可以存在多个 还是在同一个数据项中
    ## 1.可以直接添加字符
    # sequence = Point("JD") \
    #     .tag("used_percent2", 24.43234542) \
    #     .field("used_percent2", 14) \
    #     .time(datetime.utcnow(), WritePrecision.NS)
    ## 2.也可以传入对象
    # sequence= {"measurement": measurement, "tags": tags,"fields": fields}
    ## 3.直接传入   meansur    tag                 filed
    # sequence = ["h2o_feet,location=coyote_creek water_level=2.0 2",
    #              "h2o_feet,location=coyote_creek water_level=3.0 3"]



    # 写入方法2 （推荐这种）
    # point = Point("mem") \
    #     .tag("host", "host1") \
    #     .field("used_percent", 24.43234543) \
    #     .time(datetime.utcnow(), WritePrecision.NS)
    # write_api.write(bucket, org, point)
def init():
    client=creat_client()
    # 用完关闭
    # while(1):
    #     add2(client,"JD",{"upload_num":"2","download_num":"2"},[{'upload_num': 33.7429}, {'download_num': 14.5863}])
    delet(client)
    #     query(client)

    client.close()
    return "yes"


# init()

